package com.lincoln.framework.filter;

import com.lincoln.framework.bean.RewriteBean;
import com.lincoln.framework.utils.FrameworkLogger;
import com.lincoln.framework.utils.ParameterChecker;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * url重写过滤器
 * 
 * @author zwm
 * 
 * @version 2016-2-25 下午2:57:26
 */
public class RewriteFilter implements Filter {

	private static final FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(RewriteFilter.class);

	/** 维护一个到当前application的引用 */
	private static ServletContext application = null;

	private static final String HASH_URL = "cowhide.application.hash.url";

	/**
	 * 过滤器参数初始化方法，服务启动时候调用
	 */
	public void init(FilterConfig config) throws ServletException {
		application = config.getServletContext();
	}

	/**
	 * 过滤器销毁方法,服务器停止时候调用，主要是对数据的清理工作
	 */
	public void destroy() {
	}

	/**
	 * 过滤器过滤方法
	 */
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		if (ParameterChecker.isNullOrEmpty(request.getCharacterEncoding())) {
			request.setCharacterEncoding("utf-8");
		}
		chain.doFilter(servletRequest, servletResponse);
	}

	/**
	 * 获得实际访问的serverName
	 * 
	 * @return String 根据当前访问服务器域名获得实际的访问地址格式: ***.domain
	 */
	private RewriteBean getCorrespondServerName(String serverName) {
		Map<String, RewriteBean> hashURL = (Map<String, RewriteBean>) application.getAttribute(HASH_URL);
		if (hashURL != null) {
			return hashURL.get(serverName);
		}
		return null;
	}

}